package com.gqj.meter.controller;

import com.alibaba.fastjson.JSON;
import com.gqj.common.annotation.Log;
import com.gqj.common.constant.UserConstants;
import com.gqj.common.core.controller.BaseController;
import com.gqj.common.core.domain.AjaxResult;
import com.gqj.common.core.page.TableDataInfo;
import com.gqj.common.enums.BusinessType;
import com.gqj.common.utils.StorageUtil;
import com.gqj.common.utils.poi.ExcelUtil;
import com.gqj.meter.domain.MdInTaskDetails;
import com.gqj.meter.domain.MdMeter;
import com.gqj.meter.domain.vo.MdMeterVo;
import com.gqj.meter.mapper.MdInTaskDetailsMapper;
import com.gqj.meter.service.IMdMeterService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;

/**
 * 电能表Controller
 *
 * @author lxq
 * @date lxq-02-10
 */
@Api(value = "/meter/mdMeter", description = "电能表")
@RestController
@RequestMapping("/meter/mdMeter")
public class MdMeterController extends BaseController {
    @Autowired
    private IMdMeterService mdMeterService;
    @Value("${downloadPath}")
    private String downloadPath;
    @Autowired
    private MdInTaskDetailsMapper mdInTaskDetailsMapper;

    /**
     * 查询电能表列表
     */
    @ApiOperation("查询电能表列表")
    @PreAuthorize("@ss.hasPermi('meter:mdMeter:list')")
    @GetMapping("/list")
    public TableDataInfo list(MdMeter mdMeter) {
        startPage();
        List<MdMeter> list = mdMeterService.selectMdMeterList(mdMeter);
        return getDataTable(list);
    }

    /**
     * 导出电能表列表
     */
    @ApiOperation("导出电能表列表")
    @PreAuthorize("@ss.hasPermi('meter:mdMeter:export')")
    @Log(title = "电能表", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, MdMeter mdMeter) {
        List<MdMeter> list = mdMeterService.selectMdMeterList(mdMeter);
        ExcelUtil<MdMeter> util = new ExcelUtil<MdMeter>(MdMeter.class);
        util.exportExcel(response, list, "电能表数据");
    }

    /**
     * 获取电能表详细信息
     */
    @ApiOperation("获取电能表详细信息")
    @PreAuthorize("@ss.hasPermi('meter:mdMeter:query')")
    @GetMapping(value = "/{meterId}")
    public AjaxResult getInfo(@PathVariable("meterId") Long meterId) {
        return success(mdMeterService.selectMdMeterByMeterId(meterId));
    }

    /**
     * 新增电能表
     */
    @ApiOperation("新增电能表")
    @PreAuthorize("@ss.hasPermi('meter:mdMeter:add')")
    @Log(title = "电能表", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody MdMeter mdMeter) {
        if (UserConstants.NOT_UNIQUE.equals(mdMeterService.checkRfidNoUnique(mdMeter))) {
            return AjaxResult.error("新增'" + mdMeter.getRfidNo() + "'失败，条形码已存在！");
        }
        return toAjax(mdMeterService.insertMdMeter(mdMeter));
    }

    /**
     * 修改电能表
     */
    @ApiOperation("修改电能表")
    @PreAuthorize("@ss.hasPermi('meter:mdMeter:edit')")
    @Log(title = "电能表", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody MdMeter mdMeter) {
        if (null == mdMeter.getMeterId() || 0 == mdMeter.getMeterId()) {
            return AjaxResult.error("修改失败，电能表ID为空！");
        }
        if (UserConstants.NOT_UNIQUE.equals(mdMeterService.checkRfidNoUnique(mdMeter))) {
            return AjaxResult.error("修改'" + mdMeter.getRfidNo() + "'失败，条形码已存在！");
        }
        return toAjax(mdMeterService.updateMdMeter(mdMeter));
    }

    /**
     * 删除电能表
     */
    @ApiOperation("删除电能表")
    @PreAuthorize("@ss.hasPermi('meter:mdMeter:remove')")
    @Log(title = "电能表", businessType = BusinessType.DELETE)
    @DeleteMapping("/{meterIds}")
    public AjaxResult remove(@PathVariable Long[] meterIds) {
        //判断电能表是否被引用
        for (int i = 0; i < meterIds.length; i++) {
            MdMeter mdMeter = mdMeterService.selectMdMeterByMeterId(meterIds[i]);
            String serviceStatus = mdMeter.getServiceStatus();
            if (!"00".equals(serviceStatus) && !"01".equals(serviceStatus) && !"04".equals(serviceStatus)) {
                return AjaxResult.error("电能表" + mdMeter.getRfidNo() + "的业务状态不允许删除！");
            }

            //查看出入库是否引用
            MdInTaskDetails mdInTaskDetails = new MdInTaskDetails();
            mdInTaskDetails.setRfidNo(mdMeter.getRfidNo());
            mdInTaskDetails.setIsComplete("0");
            List<MdInTaskDetails> mdInTaskDetailsList = mdInTaskDetailsMapper.selectMdInTaskDetailsList(mdInTaskDetails);
            if (mdInTaskDetailsList.size() > 0) {
                return AjaxResult.error("电能表" + mdMeter.getRfidNo() + "入库任务中已经引用，无法删除！");
            }
        }

        return toAjax(mdMeterService.deleteMdMeterByMeterIds(meterIds));
    }

    /**
     * 下载电能表json文件
     */
    @ApiOperation("下载电能表json文件")
    @PreAuthorize("@ss.hasPermi('meter:mdMeter:downloadJsonMdMeter')")
    @GetMapping("/downloadJsonMdMeter")
    public AjaxResult downloadJsonMdMeter(MdMeter mdMeter) {
        List<MdMeter> mt = mdMeterService.selectMdMeterList(mdMeter);
        List<MdMeterVo> vos = StorageUtil.copyList(mt, MdMeterVo::new);

        String orderNo = StorageUtil.getOrderNoTo12();
        // 生成文件名
        String fileName = downloadPath;
        String jsonStringAc = JSON.toJSONString(vos);
        StorageUtil.createJsonFile(jsonStringAc, fileName, "电能表数据" + orderNo);

        return AjaxResult.success(fileName + "电能表数据" + orderNo);
    }

    /**
     * 导入电能表execl文件
     */
    @ApiOperation("导入电能表execl文件")
    @Log(title = "导入电能表execl文件", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('meter:mdMeter:import')")
    @PostMapping("/importDataMeter")
    public AjaxResult importDataMeter(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<MdMeter> util = new ExcelUtil<MdMeter>(MdMeter.class);
        List<MdMeter> meterList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = mdMeterService.importMeter(meterList, updateSupport, operName);
        return success(message);
    }

    @ApiOperation("下载电能表模板")
    @PostMapping("/importTemplateMeter")
    @PreAuthorize("@ss.hasPermi('meter:mdMeter:importTemplateMeter')")
    public void importTemplateMeter(HttpServletResponse response) {
        ExcelUtil<MdMeter> util = new ExcelUtil<MdMeter>(MdMeter.class);
        util.importTemplateExcel(response, "电能表数据");
    }

    /**
     * 获取储位统计信息
     */
    @ApiOperation("获取资产统计信息")
    @PreAuthorize("@ss.hasPermi('meter:mdMeter:mdMaterialStatistics')")
    @GetMapping("/getMaterialStatisticsInfo/{curStatusCode}")
    public AjaxResult getMaterialStatisticsInfo(@PathVariable String curStatusCode) {
        List<Map<String, Object>> map = mdMeterService.getMaterialStatisticsInfo(curStatusCode);
        return success(map);
    }
}
